package com.app.yc.ifapp;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.yc.ifapp.adapter.MyBaseExpandableListAdapter;
import com.app.yc.ifapp.asynctask.WebApiRequest;
import com.app.yc.ifapp.asynctask.WebApiRequestContext;
import com.app.yc.ifapp.entity.ApiResult;
import com.app.yc.ifapp.entity.Field;
import com.app.yc.ifapp.entity.IrData;
import com.app.yc.ifapp.entity.IrDevice;
import com.app.yc.ifapp.entity.Room;
import com.app.yc.ifapp.entity.Term;
import com.app.yc.ifapp.entity.UserInfo;
import com.app.yc.ifapp.utils.ApiUtils;
import com.app.yc.ifapp.utils.CastUtils;
import com.app.yc.ifapp.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class InfraredControlActivity extends Activity {

    UserInfo mUserInfo;
    String url;
    List<Room<IrDevice>> mList_Room_IrDevice;

    Drawable img_room_class;
    Drawable img_room_dormitory;
    Drawable img_room_function;
    Drawable img_room_laboratory;
    Drawable img_room_office;
    Drawable img_term_air_conditioner;
    Drawable img_term_fan;
    Drawable img_term_curtains;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_infrared_control);

        mUserInfo = getIntent().getParcelableExtra("user");
        url = getIntent().getStringExtra("url");

        //先获取到各种图标
        img_room_class = ContextCompat.getDrawable(this, R.mipmap.room_class);
        img_room_dormitory = ContextCompat.getDrawable(this, R.mipmap.room_dormitory);
        img_room_function = ContextCompat.getDrawable(this, R.mipmap.room_function);
        img_room_laboratory = ContextCompat.getDrawable(this, R.mipmap.room_laboratory);
        img_room_office = ContextCompat.getDrawable(this, R.mipmap.room_office);
        img_term_air_conditioner = ContextCompat.getDrawable(this, R.mipmap.term_air_conditioner);
        img_term_curtains = ContextCompat.getDrawable(this, R.mipmap.term_curtains);
        img_term_fan = ContextCompat.getDrawable(this, R.mipmap.term_fan);

        //获取并缩放左箭头
        Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.back_arrow);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth() / 3,
                drawable.getIntrinsicHeight() / 3);
        //获取到控件
        TextView back = (TextView) findViewById(R.id.infrared_control_back);
        //设置右箭头
        back.setCompoundDrawables(drawable, null, null, null);
        back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        WebApiRequest request = new WebApiRequest();
        request.setAsyncTaskCallBack(new WebApiRequest.AsyncTaskCallBack() {

            @Override
            public void onTaskOver(String result) {

                if (TextUtils.isEmpty(result)) {
                    Toast.makeText(InfraredControlActivity.this, R.string.error_api_fail,
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                mList_Room_IrDevice = getData(result);

                if (mList_Room_IrDevice == null || mList_Room_IrDevice.size() <= 0) {
                    Toast.makeText(InfraredControlActivity.this, R.string.error_not_relation_room,
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                //使用适配器绑定数据
                MyBaseExpandableListAdapter<Room<IrDevice>, IrDevice> adapter =
                        new MyBaseExpandableListAdapter<>(InfraredControlActivity.this,
                                R.layout.item_room,
                                R.layout.item_device,
                                mList_Room_IrDevice,
                                new InfraredControlActivity.MyBaseExpandableListAdapterCallback());
                ExpandableListView listView = (ExpandableListView) findViewById(R.id.list_room_device);
                listView.setAdapter(adapter);
            }
        });

        try {
            //构造请求登录参数
            String params = "?user_Id" + "=" +
                    URLEncoder.encode(mUserInfo.getUser_Id(), "UTF-8");
            request.execute(url + ApiUtils.GET_TERMS + params, StringUtils.EMPTY);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(InfraredControlActivity.this, R.string.error_api_fail,
                    Toast.LENGTH_SHORT).show();
        }
    }

    private List<Room<IrDevice>> getData(String json) {
        try {
            Gson gson = new Gson();
            ApiResult<List<Room<IrDevice>>> apiResult = gson.fromJson(json,
                    new TypeToken<ApiResult<List<Room<IrDevice>>>>() {
                    }.getType());
            if (apiResult != null && apiResult.getResult()) {
                if (apiResult.getData() != null && apiResult.getData().size() > 0) {
                    mList_Room_IrDevice = apiResult.getData();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mList_Room_IrDevice;
    }

    private class MyBaseExpandableListAdapterCallback
            implements MyBaseExpandableListAdapter.Callback<Room<IrDevice>, IrDevice> {

        @Override
        public void getGroupView(int i, View v, Room<IrDevice> group) {

            TextView tv_name = (TextView) v.findViewById(R.id.room_name);
            TextView tv_type = (TextView) v.findViewById(R.id.room_type);
            ImageView iv_image = (ImageView) v.findViewById(R.id.room_image);
            tv_name.setText(group.getRoom_Name());
            tv_type.setText(group.getRoom_Type());
            iv_image.setTag(i);
            iv_image.setImageDrawable(getRoomImg(group.getRoom_Type()));

            if (group.getIrDevices() == null) {
                group.setIrDevices(new ArrayList<IrDevice>());
            }
            group.setChild(group.getIrDevices());
        }

        @Override
        public void getChildView(int i, View v, Room<IrDevice> group, IrDevice child) {
            TextView tv_name = (TextView) v.findViewById(R.id.device_name);
            TextView tv_type = (TextView) v.findViewById(R.id.device_type);
            ImageView iv = (ImageView) v.findViewById(R.id.device_image);
            Button bv1 = (Button) v.findViewById(R.id.device_button_1);
            Button bv2 = (Button) v.findViewById(R.id.device_button_2);
            Button bv3 = (Button) v.findViewById(R.id.device_button_3);

            bv1.setTag(R.id.id_device, child);
            bv1.setTag(R.id.id_room, group);
            bv1.setTag(R.id.id_mode, "开");
            bv1.setOnClickListener(new OnAndOffButtonClick());

            bv2.setTag(R.id.id_device, child);
            bv2.setTag(R.id.id_room, group);
            bv2.setTag(R.id.id_mode, "关");
            bv2.setOnClickListener(new OnAndOffButtonClick());

            tv_name.setText(child.getDevice_Model());
            tv_type.setText(child.getDevice_Brand() + "-" +
                    child.getDevice_Type());

            bv1.setText(R.string.text_open);
            bv2.setText(R.string.text_close);

            bv1.setVisibility(View.VISIBLE);
            bv2.setVisibility(View.VISIBLE);
            bv3.setVisibility(View.VISIBLE);

            switch (child.getDevice_Type()) {
                case "空调":
                    bv3.setText(R.string.text_control);
                    iv.setImageDrawable(img_term_air_conditioner);
                    break;
                case "风扇":
                    bv3.setText(R.string.text_control);
                    iv.setImageDrawable(img_term_fan);
                    break;
                default:
                    bv3.setVisibility(View.GONE);
                    iv.setImageDrawable(null);
                    break;
            }
        }
    }

    /*
     * 打开与关闭按钮点击事件
     */
    private class OnAndOffButtonClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            Room<IrDevice> room = CastUtils.cast(v.getTag(R.id.id_room));
            IrDevice device = (IrDevice) v.getTag(R.id.id_device);
            String mode = (String) v.getTag(R.id.id_mode);

            String ir_No = StringUtils.EMPTY;
            List<String> params = new ArrayList<>();

            try {
                //查找红外数据
                for (IrData data : device.getIr_Datas()
                     ) {
                    if (data.getIr_Data_Name() != null && data.getIr_Data_Name().contains(mode)) {
                        ir_No = Integer.toString(data.getIr_Data_No());
                        break;
                    }
                }

                //没有红外数据则跳出
                if (StringUtils.isNullOrEmpty(ir_No)) {
                    Toast.makeText(InfraredControlActivity.this,
                            R.string.error_not_exists_ir_data,
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                //查找所有红外控制器
                for (Term term : room.getTerms()
                     ) {
                    if (term.getTermTypeId() == 11) {
                        String param = "?user_Id=" + URLEncoder.encode(mUserInfo.getUser_Id(), "UTF-8") +
                                "&sn=" + term.getTermSn() +
                                "&ir_No=" + ir_No;
                        params.add(param);
                    }
                }

                //没有红外控制器则跳出
                if (params.size() <= 0) {
                    Toast.makeText(InfraredControlActivity.this,
                            R.string.error_not_exists_ir_term,
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                for (String param : params
                     ) {
                    WebApiRequestContext<Button> request = new WebApiRequestContext<>((Button) v);
                    request.setAsyncTaskCallBack(new WebApiRequestContext.AsyncTaskCallBack<Button>() {

                        @Override
                        public void onTaskOver(String result, Button context) {
                            context.setEnabled(true);
                            try {
                                Gson gson = new Gson();
                                ApiResult<List<Field>> apiResult = gson.fromJson(result,
                                        new TypeToken<ApiResult<List<Field>>>() {
                                        }.getType());
                                if (apiResult == null) {
                                    Toast.makeText(InfraredControlActivity.this,
                                            R.string.error_api_fail,
                                            Toast.LENGTH_SHORT).show();
                                    return;
                                }

                                if (apiResult.getMessage() != null) {
                                    Toast.makeText(InfraredControlActivity.this,
                                            apiResult.getMessage(),
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(InfraredControlActivity.this,
                                            R.string.error_api_fail,
                                            Toast.LENGTH_SHORT).show();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    v.setEnabled(false);
                    request.execute(url + ApiUtils.TASK_IR_CONTROL + param, StringUtils.EMPTY);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(InfraredControlActivity.this, R.string.error_api_fail,
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    /*
 * 获取房间的图标
 */
    private Drawable getRoomImg(String type) {
        switch (type) {
            case "教室": return img_room_class;
            case "实验室": return img_room_laboratory;
            case "宿舍": return img_room_dormitory;
            case "办公室": return img_room_office;
            case "功能室": return img_room_function;
        }

        return  null;
    }
}
